
package com.jf.cloud.search.listener;

import cn.throwx.canal.gule.model.CanalBinLogResult;
import com.jf.cloud.api.order.bo.EsPurchaseOrderBO;
import com.jf.cloud.api.order.feign.PurchaseOrderFeignClient;
import com.jf.cloud.common.exception.LuckException;
import com.jf.cloud.common.response.ServerResponseEntity;
import com.jf.cloud.search.bo.PurchaseOrderBO;
import com.jf.cloud.search.constant.EsIndexEnum;
import com.jf.cloud.search.util.EsSearchUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * @author zz
 * @date 2020/11/13
 */
@Component
public class PurchaseOrderCanalListener extends BaseCanalBinlogEventThrowExceptionProcessor<PurchaseOrderBO> {

    private static final Logger log = LoggerFactory.getLogger(PurchaseOrderCanalListener.class);

    @Autowired
    private PurchaseOrderFeignClient purchaseOrderFeignClient;

    /**
     * 插入商品，此时插入es
     */
    @Override
    protected void processInsertInternal(CanalBinLogResult<PurchaseOrderBO> result) {
        Long orderId = result.getPrimaryKey();
        EsPurchaseOrderBO purchaseOrderBO = getEsOrderData(orderId);
        if (Objects.isNull(purchaseOrderBO)) {
            log.error("采购订单信息异常的订单id为：{}", orderId);
            return;
        }
        EsSearchUtil.esSave(purchaseOrderBO.getPurchaseOrderId(),EsIndexEnum.PURCHASE_ORDER, purchaseOrderBO);
    }

    /**
     * 更新订单数据
     */
    @Override
    protected void processUpdateInternal(CanalBinLogResult<PurchaseOrderBO> result) {
        PurchaseOrderBO afterData = result.getAfterData();
        EsPurchaseOrderBO purchaseOrderBO = getEsOrderData(afterData.getPurchaseOrderId());
        if (Objects.isNull(purchaseOrderBO)) {
            log.error("采购订单信息异常的订单id为：{}", afterData.getPurchaseOrderId());
            return;
        }
        EsSearchUtil.esUpdate(purchaseOrderBO.getPurchaseOrderId(),EsIndexEnum.PURCHASE_ORDER, purchaseOrderBO);
    }

    private EsPurchaseOrderBO getEsOrderData(Long orderId) {
        ServerResponseEntity<EsPurchaseOrderBO> orderResponseEntity = purchaseOrderFeignClient.saveMongoAndGetEsInfo(orderId);
        if (orderResponseEntity.isFail()) {
            throw new LuckException(orderResponseEntity.getMsg());
        }
        // 添加es中保存的采购订单数据
        return orderResponseEntity.getData();
    }
}
